package com.nba.common.tools;

import com.alibaba.simpleimage.render.ScaleParameter.Algorithm;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Label;
import java.awt.MediaTracker;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.MemoryImageSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.springframework.core.io.ClassPathResource;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.tasks.io.FileImageSource;

public class ImageCompress extends Frame {
    private static final long serialVersionUID = 48L;
    private static final String version = "ImageCompress v1.0";
    private Panel mControlPanel;
    private BufferedImage mBufferedImage;

    /*
     * public static void main(String[] args) { String fileName =
     * "F:/af4496a4-15ae-47c9-8279-6e095ebfd539.png"; String gui = ""; if (args.length > 0) {
     * fileName = args[0]; } if (args.length > 1) { gui = "gui"; } if (gui.equals("gui")) { new
     * ImageCompress(fileName); } else { long c = System.currentTimeMillis(); ImageScale(fileName,
     * fileName + "-s." + getFileExt(fileName).toLowerCase(), 160, 160);
     * System.out.println("elapse time:" + (float)(System.currentTimeMillis() - c) / 1000.0F + "s");
     * } }
     */

    public static class BmpReader {
        public void reader(String file) {
            try {
                InputStream in = new FileInputStream(file);
                Image TheImage = read(in);
                int wideth = TheImage.getWidth(null);
                int height = TheImage.getHeight(null);
                BufferedImage tag = new BufferedImage(wideth / 2, height / 2, BufferedImage.TYPE_INT_RGB);
                tag.getGraphics().drawImage(TheImage, 0, 0, wideth / 2, height / 2, null);
                FileOutputStream out = new FileOutputStream(file + ".jpg");
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(tag);
                out.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }

        public static int constructInt(byte[] in, int offset) {
            int ret = ((int) in[offset + 3] & 0xff);
            ret = (ret << 8) | ((int) in[offset + 2] & 0xff);
            ret = (ret << 8) | ((int) in[offset + 1] & 0xff);
            ret = (ret << 8) | ((int) in[offset + 0] & 0xff);
            return (ret);
        }

        public static int constructInt3(byte[] in, int offset) {
            int ret = 0xff;
            ret = (ret << 8) | ((int) in[offset + 2] & 0xff);
            ret = (ret << 8) | ((int) in[offset + 1] & 0xff);
            ret = (ret << 8) | ((int) in[offset + 0] & 0xff);
            return (ret);
        }

        public static long constructLong(byte[] in, int offset) {
            long ret = ((long) in[offset + 7] & 0xff);
            ret |= (ret << 8) | ((long) in[offset + 6] & 0xff);
            ret |= (ret << 8) | ((long) in[offset + 5] & 0xff);
            ret |= (ret << 8) | ((long) in[offset + 4] & 0xff);
            ret |= (ret << 8) | ((long) in[offset + 3] & 0xff);
            ret |= (ret << 8) | ((long) in[offset + 2] & 0xff);
            ret |= (ret << 8) | ((long) in[offset + 1] & 0xff);
            ret |= (ret << 8) | ((long) in[offset + 0] & 0xff);
            return (ret);
        }

        public static double constructDouble(byte[] in, int offset) {
            long ret = constructLong(in, offset);
            return (Double.longBitsToDouble(ret));
        }

        public static short constructShort(byte[] in, int offset) {
            short ret = (short) ((short) in[offset + 1] & 0xff);
            ret = (short) ((ret << 8) | (short) ((short) in[offset + 0] & 0xff));
            return (ret);
        }

        static class BitmapHeader {
            public int iSize, ibiSize, iWidth, iHeight, iPlanes, iBitcount, iCompression, iSizeimage, iXpm, iYpm, iClrused, iClrimp;

            // 读取bmp文件头信息
            public void read(InputStream fs) throws IOException {
                final int bflen = 14;
                byte bf[] = new byte[bflen];
                fs.read(bf, 0, bflen);
                final int bilen = 40;
                byte bi[] = new byte[bilen];
                fs.read(bi, 0, bilen);
                iSize = constructInt(bf, 2);
                ibiSize = constructInt(bi, 2);
                iWidth = constructInt(bi, 4);
                iHeight = constructInt(bi, 8);
                iPlanes = constructShort(bi, 12);
                iBitcount = constructShort(bi, 14);
                iCompression = constructInt(bi, 16);
                iSizeimage = constructInt(bi, 20);
                iXpm = constructInt(bi, 24);
                iYpm = constructInt(bi, 28);
                iClrused = constructInt(bi, 32);
                iClrimp = constructInt(bi, 36);
            }
        }

        public static Image read(InputStream fs) {
            try {
                BitmapHeader bh = new BitmapHeader();
                bh.read(fs);
                if (bh.iBitcount == 24) {
                    return (readImage24(fs, bh));
                }
                if (bh.iBitcount == 32) {
                    return (readImage32(fs, bh));
                }
                fs.close();
            } catch (IOException e) {
                System.out.println(e);
            }
            return (null);
        }

        // 24位
        protected static Image readImage24(InputStream fs, BitmapHeader bh) throws IOException {
            Image image;
            if (bh.iSizeimage == 0) {
                bh.iSizeimage = ((((bh.iWidth * bh.iBitcount) + 31) & ~31) >> 3);
                bh.iSizeimage *= bh.iHeight;
            }
            int npad = (bh.iSizeimage / bh.iHeight) - bh.iWidth * 3;
            int ndata[] = new int[bh.iHeight * bh.iWidth];
            byte brgb[] = new byte[(bh.iWidth + npad) * 3 * bh.iHeight];
            fs.read(brgb, 0, (bh.iWidth + npad) * 3 * bh.iHeight);
            int nindex = 0;
            for (int j = 0; j < bh.iHeight; j++) {
                for (int i = 0; i < bh.iWidth; i++) {
                    ndata[bh.iWidth * (bh.iHeight - j - 1) + i] = constructInt3(brgb, nindex);
                    nindex += 3;
                }
                nindex += npad;
            }
            image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(bh.iWidth, bh.iHeight, ndata, 0, bh.iWidth));
            fs.close();
            return (image);
        }

        // 32位
        protected static Image readImage32(InputStream fs, BitmapHeader bh) throws IOException {
            Image image;
            int xwidth = bh.iSizeimage / bh.iHeight;
            int ndata[] = new int[bh.iHeight * bh.iWidth];
            byte brgb[] = new byte[bh.iWidth * 4 * bh.iHeight];
            fs.read(brgb, 0, bh.iWidth * 4 * bh.iHeight);
            int nindex = 0;
            for (int j = 0; j < bh.iHeight; j++) {
                for (int i = 0; i < bh.iWidth; i++) {
                    ndata[bh.iWidth * (bh.iHeight - j - 1) + i] = constructInt3(brgb, nindex);
                    nindex += 4;
                }
            }
            image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(bh.iWidth, bh.iHeight, ndata, 0, bh.iWidth));
            fs.close();
            return (image);
        }

        public static Image load(String sdir, String sfile) {
            return (load(sdir + sfile));
        }

        public static Image load(String sdir) {
            try {
                FileInputStream fs = new FileInputStream(sdir);
                return (read(fs));
            } catch (IOException ex) {
                return (null);
            }
        }

        public ImageIcon getBmpImageIcon(InputStream in) throws IOException {
            Image TheImage = read(in);
            return new ImageIcon(TheImage);
        }
    }

    public ImageCompress(String fileName) {
        super("ImageCompress v1.0");
        this.file = fileName;
        createUI();
        loadImage(fileName);
        setVisible(true);
    }

    private Label labelWidth = new Label("width:");
    private TextField textWidth = new TextField(7);
    private Label labelHeight = new Label("height:");
    private TextField textHeight = new TextField(7);
    private String file;

    private void createUI() {
        setFont(new Font("Serif", 0, 12));


        setLayout(new BorderLayout());


        Label statusLabel = new Label("Welcome to ImageCompress v1.0.");

        this.textWidth.setText("160");
        this.textHeight.setText("160");

        Button loadButton = new Button("Load...");


        loadButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                FileDialog fd = new FileDialog(ImageCompress.this);
                fd.setVisible(true);
                if (fd.getFile() == null) {
                    return;
                }
                String path = fd.getDirectory() + fd.getFile();
                ImageCompress.this.file = path;
                ImageCompress.this.loadImage(path);
            }
        });
        Button buttonResize = new Button("Resize");
        buttonResize.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                ImageCompress.this.resizeImage(ImageCompress.this.file);
            }
        });
        this.mControlPanel = new Panel();
        this.mControlPanel.add(loadButton);
        this.mControlPanel.add(this.labelWidth);
        this.mControlPanel.add(this.textWidth);
        this.mControlPanel.add(this.labelHeight);
        this.mControlPanel.add(this.textHeight);
        this.mControlPanel.add(buttonResize);

        this.mControlPanel.add(statusLabel);
        add(this.mControlPanel, "South");

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                ImageCompress.this.dispose();
                System.exit(0);
            }
        });
    }

    private void resizeImage(String fileName) {
        try {
            Image image = ImageIO.read(new File(this.file));
            int imageWidth = image.getWidth(null);
            int imageHeight = image.getHeight(null);

            float scale = getRatio(imageWidth, imageHeight, Integer.parseInt(this.textWidth.getText()), Integer.parseInt(this.textWidth.getText()));
            imageWidth = (int) (scale * imageWidth);
            imageHeight = (int) (scale * imageHeight);

            image = image.getScaledInstance(imageWidth, imageHeight, 16);

            this.mBufferedImage = new BufferedImage(imageWidth, imageHeight, 1);
            Graphics2D g2 = this.mBufferedImage.createGraphics();



            g2.drawImage(image, 0, 0, imageWidth, imageHeight, Color.white, null);

            float[] kernelData2 = {-0.125F, -0.125F, -0.125F, -0.125F, 2.0F, -0.125F, -0.125F, -0.125F, -0.125F};
            Kernel kernel = new Kernel(3, 3, kernelData2);
            ConvolveOp cOp = new ConvolveOp(kernel, 1, null);
            this.mBufferedImage = cOp.filter(this.mBufferedImage, null);
            repaint();
        } catch (IOException localIOException) {
        }
    }

    private void loadImage(String fileName) {
        Image image = Toolkit.getDefaultToolkit().getImage(fileName);
        MediaTracker mt = new MediaTracker(this);
        mt.addImage(image, 0);
        try {
            mt.waitForID(0);
        } catch (InterruptedException ie) {
            return;
        }
        if (mt.isErrorID(0)) {
            return;
        }
        this.mBufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), 1);
        Graphics2D g2 = this.mBufferedImage.createGraphics();
        g2.drawImage(image, null, null);
        adjustToImageSize();
        center();
        validate();
        repaint();
        setTitle("ImageCompress v1.0: " + fileName);
    }

    private void adjustToImageSize() {
        if (!isDisplayable()) {
            addNotify();
        }
        Insets insets = getInsets();
        int imageWidth = this.mBufferedImage.getWidth();
        int imageHeight = this.mBufferedImage.getHeight();
        imageWidth = 600;
        imageHeight = 550;
        int w = imageWidth + insets.left + insets.right;
        int h = imageHeight + insets.top + insets.bottom;
        h += this.mControlPanel.getPreferredSize().height;
        setSize(w, h);
    }

    private void center() {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension d = getSize();
        int x = (screen.width - d.width) / 2;
        int y = (screen.height - d.height) / 2;
        setLocation(x, y);
    }

    public void paint(Graphics g) {
        if (this.mBufferedImage == null) {
            return;
        }
        Insets insets = getInsets();
        g.drawImage(this.mBufferedImage, insets.left, insets.top, null);
    }

    /**
     * 缩小输出图片
     * 
     * @param sourceImage
     * @param width
     * @param height
     * @param quality
     * @param destFile
     * @throws IOException
     */
    private static BufferedImage resizeImage(final BufferedImage sourceImage, final int width, final int height, final float quality)
            throws IOException {
        try {
            Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(sourceImage).size(width, height).keepAspectRatio(false).outputQuality(quality);
            return builder.asBufferedImage();
        } catch (IllegalStateException e) {
            Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(sourceImage).size(width, height).keepAspectRatio(false);
            return builder.asBufferedImage();
        }
    }

    // 把原图转换成二进制
    private static byte[] toByteArray(InputStream input) {
        if (input == null) {
            return null;
        }
        ByteArrayOutputStream output = null;
        byte[] result = null;
        try {
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 100];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
            }
            result = output.toByteArray();
            if (output != null) {
                output.close();
            }
        } catch (Exception e) {
        }
        return result;
    }

    // 把二进制转换成图片
    private static BufferedImage toBufferedImage(byte[] imagedata) throws IOException {
        Image image = Toolkit.getDefaultToolkit().createImage(imagedata);
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        image = new ImageIcon(image).getImage();
        if (image.getWidth(null) <= 0) {
            // 转换
            BmpReader reader = new BmpReader();
            InputStream input = new ByteArrayInputStream(imagedata);
            ImageIcon icon = reader.getBmpImageIcon(input);
            image = icon.getImage();
        }
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
        }
        if (bimage == null) {
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
        Graphics g = bimage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

    public static void ImageScale(String sourceImg, String targetImg, int width, int height) {
        try {
            File f = new File(sourceImg);
            InputStream in = new FileInputStream(f);
            byte[] imageData = toByteArray(in);
            BufferedImage mBufferedImage = toBufferedImage(imageData);

            mBufferedImage = resizeImage(mBufferedImage, width, height, 1);

            float[] kernelData2 = {-0.125F, -0.125F, -0.125F, -0.125F, 2.0F, -0.125F, -0.125F, -0.125F, -0.125F};
            Kernel kernel = new Kernel(3, 3, kernelData2);
            ConvolveOp cOp = new ConvolveOp(kernel, 1, null);
            mBufferedImage = cOp.filter(mBufferedImage, null);
            FileOutputStream out = new FileOutputStream(targetImg);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(mBufferedImage);
            out.close();
        } catch (FileNotFoundException localFileNotFoundException) {
        } catch (IOException localIOException) {
        }
    }
    
    public static void ImageScale(InputStream sourceFileStream, String savePath, String fileName, String imgExt, String imgSize, int width, int height) {
        try {
            //File f = new File(sourceImg);
            //InputStream in = new FileInputStream(sourceFile);
            byte[] imageData = toByteArray(sourceFileStream);
            BufferedImage mBufferedImage = toBufferedImage(imageData);
            mBufferedImage = resizeImage(mBufferedImage, width, height, 1);

            float[] kernelData2 = {-0.125F, -0.125F, -0.125F, -0.125F, 2.0F, -0.125F, -0.125F, -0.125F, -0.125F};
            Kernel kernel = new Kernel(3, 3, kernelData2);
            ConvolveOp cOp = new ConvolveOp(kernel, 1, null);
            mBufferedImage = cOp.filter(mBufferedImage, null);
            //
            String fullPath = savePath +File.separator+ imgSize ;
            File createFile = new File(fullPath);
            if (!createFile.exists()) {
                createFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(fullPath +File.separator+fileName+"."+imgExt);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(mBufferedImage);
            out.close();
        } catch (FileNotFoundException localFileNotFoundException) {
        } catch (IOException localIOException) {
        }
    }
/*
    public static String ImageSave(String sourceImg, String imgroot) {
        try {
            URL sourceFile = new URL(imgroot + sourceImg);
            HttpURLConnection connection = (HttpURLConnection) sourceFile.openConnection();
            InputStream in = connection.getInputStream();

            byte[] imageData = toByteArray(in);
            BufferedImage mBufferedImage = toBufferedImage(imageData);

            float[] kernelData2 = {-0.125F, -0.125F, -0.125F, -0.125F, 2.0F, -0.125F, -0.125F, -0.125F, -0.125F};
            Kernel kernel = new Kernel(3, 3, kernelData2);
            ConvolveOp cOp = new ConvolveOp(kernel, 1, null);
            mBufferedImage = cOp.filter(mBufferedImage, null);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(mBufferedImage, CommUtil.FILEEXTNAME, os);

            long d = Long.valueOf(os.size() + "");// 水印后文件大小
            InputStream inStream = new ByteArrayInputStream(os.toByteArray());
            ClientGlobal.init(new ClassPathResource("fdfs_client.conf").getFile().getPath());
            byte[] fileBuff = getFileBuffer(inStream, d);

            return CommUtil.saveFileToServer(fileBuff);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
*/
    //"http://192.168.140.176:8080/pic/","d:/.....","griWKA412","s", "jpg",300,300
    public static void ImageScale(String imgpath, String savePath, String fileName, String imgSize, String imgExt, int width, int height) throws URISyntaxException {
        try {
            //
            String fullPath = savePath +File.separator+ imgSize ;
            File createFile = new File(fullPath);
            if (!createFile.exists()) {
                createFile.mkdirs();
            }
            //
            URL sourceFile = new URL(imgpath + fileName +"."+ imgExt);
            HttpURLConnection connection = (HttpURLConnection) sourceFile.openConnection();
            InputStream in = connection.getInputStream();
            byte[] imageData = toByteArray(in);
            BufferedImage mBufferedImage = toBufferedImage(imageData);
            mBufferedImage = resizeImage(mBufferedImage, width, height, 1);
            
            float[] kernelData2 = {-0.125F, -0.125F, -0.125F, -0.125F, 2.0F, -0.125F, -0.125F, -0.125F, -0.125F};
            Kernel kernel = new Kernel(3, 3, kernelData2);
            ConvolveOp cOp = new ConvolveOp(kernel, 1, null);
            mBufferedImage = cOp.filter(mBufferedImage, null);
            FileOutputStream out = new FileOutputStream(savePath +File.separator+ imgSize+File.separator+fileName+"."+imgExt);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(mBufferedImage);
            out.close();
        } catch (FileNotFoundException localFileNotFoundException) {
            localFileNotFoundException.printStackTrace();
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
    }

    
     public static void main(String[] args) {
         //"http://192.168.140.176:8080/pic/","d:/.....","griWKA412","s", "jpg",300,300
         try {
            ImageScale("http://localhost:7777/nba/uploadfile/pic/","D:\\tomcat\\apache-tomcat-7.0.62_7777\\webapps\\nba\\uploadfile\\pic", "8a86c193535917670153596428d10011", "s", "jpg", 300, 300);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
     }
    
    /**
     * @author zhangdd 已知InputStream长度，将其转换为byte[]
     * @param inStream
     * @param fileLength
     * @return
     * @throws IOException
     */
    public static byte[] getFileBuffer(InputStream inStream, long fileLength) throws IOException {

        byte[] buffer = new byte[256 * 1024];
        byte[] fileBuffer = new byte[(int) fileLength];

        int count = 0;
        int length = 0;

        while ((length = inStream.read(buffer)) != -1) {
            for (int i = 0; i < length; ++i) {
                fileBuffer[count + i] = buffer[i];
            }
            count += length;
        }
        return fileBuffer;
    }


    public static float getRatio(int width, int height, int maxWidth, int maxHeight) {
        float Ratio = 1.0f;


        float widthRatio = maxWidth * 1.0f / width * 1.0f;
        float heightRatio = maxHeight * 1.0f / height * 1.0f;
        if ((widthRatio < 1.0f) || (heightRatio < 1.0f)) {
            Ratio = widthRatio <= heightRatio ? widthRatio : heightRatio;
        }
        return Ratio;
    }

    public static String getFileExt(String filePath) {
        String tmp = filePath.substring(filePath.lastIndexOf(".") + 1);
        return tmp.toUpperCase();
    }

    public static String getFileName(String filePath) {
        int pos = -1;
        int endPos = -1;
        if (!filePath.equals("")) {
            if (filePath.lastIndexOf("/") != -1) {
                pos = filePath.lastIndexOf("/") + 1;
            } else if (filePath.lastIndexOf("//") != -1) {
                pos = filePath.lastIndexOf("//") + 1;
            }
            if (pos == -1) {
                pos = 0;
            }
            filePath = filePath.substring(pos);
            endPos = filePath.lastIndexOf(".");
            if (endPos == -1) {
                return filePath;
            }
            return filePath.substring(0, endPos);
        }
        return "";
    }

    public static String getFileFullName(String filePath) {
        int pos = -1;
        if (!filePath.equals("")) {
            if (filePath.lastIndexOf("/") != -1) {
                pos = filePath.lastIndexOf("/") + 1;
            } else if (filePath.lastIndexOf("//") != -1) {
                pos = filePath.lastIndexOf("//") + 1;
            }
            if (pos == -1) {
                pos = 0;
            }
            return filePath.substring(pos);
        }
        return "";
    }

    public static String getFilePath(String filePath) {
        int pos = -1;
        if (!filePath.equals("")) {
            if (filePath.lastIndexOf("/") != -1) {
                pos = filePath.lastIndexOf("/") + 1;
            } else if (filePath.lastIndexOf("//") != -1) {
                pos = filePath.lastIndexOf("//") + 1;
            }
            if (pos != -1) {
                return filePath.substring(0, pos);
            }
            return "";
        }
        return "";
    }

    /**
     * 执行裁剪上传
     * 
     * @param sourceImg 图片名称
     * @param imgroot 根路径
     * @param width 宽
     * @param height 高
     * @throws Exception
     */
   /* public static void ImageToScale(String sourceImg, String imgroot, String imgSize, int width, int height) throws Exception {
        URL sourceFile = null;
        ByteArrayOutputStream baoutput = null;
        TrackerServer trackerServer = null;
        try {
            sourceFile = new URL(imgroot + sourceImg);
            baoutput = new ByteArrayOutputStream();
            // 执行图片裁剪功能
            SimpleImgUtil.doScale(sourceFile.openStream(), baoutput, width, height, Algorithm.INTERP_BICUBIC);

            ClientGlobal.init(new ClassPathResource("fdfs_client.conf").getFile().getPath());

            // 建立连接
            TrackerClient tracker = new TrackerClient();
            trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);

            // 设置元信息
            NameValuePair[] metaList = new NameValuePair[2];
            metaList[0] = new NameValuePair("fileExtName", CommUtil.FILEEXTNAME);
            metaList[1] = new NameValuePair("fileLength", String.valueOf(baoutput.toByteArray().length));
            // 指定prefix
            String prefix_name = imgSize;
            client.upload_file1(sourceImg, prefix_name, baoutput.toByteArray(), CommUtil.FILEEXTNAME, metaList);
        } finally {
            // 关闭连接
            if (trackerServer != null) {
                trackerServer.close();
                trackerServer = null;
            }
            if (baoutput != null) {
                baoutput.close();
                baoutput = null;
            }
        }
    }*/

}
